package com.tbl.modules.wms.controller.baseinfo;

import com.alibaba.fastjson.JSON;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.baseinfo.Dish;
import com.tbl.modules.wms.service.baseinfo.DishService;
import com.tbl.modules.wms.service.webservice.client.WmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 盘具控制层
 * @author 70486
 */
@RestController
@RequestMapping(value = "/dish")
public class DishController extends AbstractController {

    /**
     * 日志信息
     */
	@Autowired
	private LogService logService;
    /**
     * 角色
     */
    @Autowired
    private RoleService roleService;
    /**
     * 盘具
     */
    @Autowired
    private DishService dishService;
    /**
     * wms调用入口
     */
    @Autowired
    private WmsService wmsService;

    /**
     * 跳转到盘展示列表
     * @return MpdelAndView
     */
    @RequestMapping(value = "/toList")
    @ResponseBody
     public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.dish));
        mv.setViewName("techbloom/baseinfo/dish/dish_list");
        return mv;
    }

    /**
     * 获取盘具列表数据
     * @param queryJsonString 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(3);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = dishService.getPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }
    
    /**
     * 弹出到编辑页面
     * @param id 盘具主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toAdd.do")
    @ResponseBody
    public ModelAndView toAdd(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/baseinfo/dish/dish_edit");
        if (id != null && id != 0L) {
            mv.addObject("dish", dishService.selectById(id));
        } else {
            Dish dish = new Dish();
            mv.addObject("dish", dish);
        }
        mv.addObject("edit", Constant.INT_ONE);
        return mv;
    }
    
    /**
     * 保存盘具信息
     * @param dish 盘具实体
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/saveDish")
    @ResponseBody
    public Map<String, Object> saveDish(Dish dish) {
        Map<String, Object> map = new HashMap<>(2);
        boolean result=dishService.insertOrUpdate(dish);
        map.put("result", result);
        map.put("msg",result?"保存成功！":"保存失败！");
        return map;
    }
    
    /**
     * 导出Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            String sheetName = "盘具清单" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            String [] excelIndexArray = request.getParameter("queryExportExcelIndex").split(",");

            if (excelIndexArray.length==1&&"".equals(excelIndexArray[0])) {
                mapFields.put("code", "盘具编码");
                mapFields.put("model", "规格型号");
                mapFields.put("drumType", "盘具类型");
                mapFields.put("drumTypeDetail", "盘具子类型");
                mapFields.put("outerDiameter", "盘具外径");
                mapFields.put("innerDiameter", "盘具内径");
                mapFields.put("oneMax", "L1MAX");
                mapFields.put("two", "L2");
                mapFields.put("maxCarry", "最大负重");
            }else {
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("code", "盘具编码");
                    } else if ("3".equals(s)) {
                        mapFields.put("model", "规格型号");
                    } else if ("4".equals(s)) {
                        mapFields.put("drumType", "盘具类型");
                    } else if ("5".equals(s)) {
                        mapFields.put("drumTypeDetail", "盘具子类型");
                    } else if ("6".equals(s)) {
                        mapFields.put("outerDiameter", "盘具外径");
                    } else if ("7".equals(s)) {
                        mapFields.put("innerDiameter", "盘具内径");
                    } else if ("8".equals(s)) {
                        mapFields.put("oneMax", "L1MAX");
                    } else if ("9".equals(s)) {
                        mapFields.put("two", "L2");
                    } else if ("10".equals(s)) {
                        mapFields.put("maxCarry", "最大负重");
                    }
                }
            }

            DeriveExcel.exportExcel(sheetName, dishService.getExcelList(request.getParameter("ids"), request.getParameter("queryCode")),
                    mapFields, response, "");
            logService.logInsert("盘具导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 删除盘具信息
     * @param ids 盘具主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/deleteDish.do")
    @ResponseBody
    public Map<String, Object> deleteDish(String ids) {
        Map<String, Object> map = new HashMap<>(2);
        boolean result = dishService.deleteBatchIds(Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList()));
        map.put("result", result);
        map.put("msg", result?"删除成功！":"删除失败！");
        return map;
    }
    
    /**
     * 同步盘具基础数据
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/synchronousdata.do")
    @ResponseBody
    public Map<String,Object> synchronousdata() {
    	Map<String, Object> returnMap = new HashMap<>(2);
    	try {
			logger.info(DateUtils.getTime()+" >>同步盘具基础数据....");
            Map<String, Object> xmlMap = new HashMap<>(1);
		    xmlMap.put("line", new HashMap<String, Object>(8) {{
		        put("code", "1");
		        put("innerdiameter", "1");
		        put("outerdiameter", "1");
		        put("maxcarry", "1");
		        put("model", "1");
		        put("type", "1");
		        put("onemax", "1");
		        put("two", "1");
		    }});
	        wmsService.FEWMS019(xmlMap);
			return new HashMap<String,Object>(2) {{
				put("result", true);
				put("msg", "更新成功！");
			}};
		} catch (Exception e) {
			e.printStackTrace();
			returnMap.put("result", false);
			returnMap.put("msg", "同步失败，请联系管理员查看！");
			return returnMap;
		}
        
    }
}
